package com.ls.lserp.modules.sys.utils;

import com.ls.lserp.dbaccess.Dao.AccessTokenEntityMapper;
import com.ls.lserp.dbaccess.Entity.AccessTokenEntity;
import com.ls.lserp.modules.sys.entity.WeiXinPushMessageEntity;
import com.ls.lserp.common.utils.SpringContextHolder;

import org.activiti.engine.impl.util.json.JSONException;
import org.activiti.engine.impl.util.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.*;
import java.io.InputStream;
import java.net.URL;

public class CommonWeChat {
	
    private static final String TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
    
    // 模板id
    /**
     * 订单支付成功通知
     */
    public static final String TEMPLATE_ID_PAID = "wnn9wpCygzwqBj5irnXB8quAF7SCGAdHZSeLkrCFAYU";
    /**
     * 已开始定制生产通知
     */
    public static final String TEMPLATE_ID_PRODUCTING = "nVvnxj7Wnw3H6BO5L-c6zm2sBb5MOFWiC5heIQOOLYw";
    /**
     * 订单发货提醒
     */
    public static final String TEMPLATE_ID_EXPRESS = "vxd8Zk36ruZsba6kVq-b0oarEXrAmyZ96ksLYVQuPCA";
    
    /**
     * 日志对象
     */
    private static Logger logger = LoggerFactory.getLogger(CommonWeChat.class);

    private static AccessTokenEntityMapper accessTokenEntityMapper = SpringContextHolder.getBean(AccessTokenEntityMapper.class);
    
    /**
     * 
     * @param dataInfo
     * @param template_id
     * @return
     */
    public static JSONObject setData(WeiXinPushMessageEntity dataInfo) {
    	JSONObject data = new JSONObject();
        try {
        	if (dataInfo != null) {
        			//JSONObject data_f = new JSONObject();
        			JSONObject data_1 = new JSONObject();
        			JSONObject data_2 = new JSONObject();
        			JSONObject data_3 = new JSONObject();
        			JSONObject data_4 = new JSONObject();
        			JSONObject data_5 = new JSONObject();
        			JSONObject data_6 = new JSONObject();
        			JSONObject data_7 = new JSONObject();
        			JSONObject data_8 = new JSONObject();
        			//JSONObject data_r = new JSONObject();
        			// 设置data
        			//data_f.put("value", dataInfo.getFirst());
        			data_1.put("value", dataInfo.getKeyword_1());
        			data_2.put("value", dataInfo.getKeyword_2());
        			data_3.put("value", dataInfo.getKeyword_3());
        			data_4.put("value", dataInfo.getKeyword_4());
        			data_5.put("value", dataInfo.getKeyword_5());
        			data_6.put("value", dataInfo.getKeyword_6());
        			data_7.put("value", dataInfo.getKeyword_7());
        			data_8.put("value", dataInfo.getKeyword_8());
        			//data_r.put("value", dataInfo.getRemark());
        			// 设置样式
        			//data_f.put("color", dataInfo.getFirstColor());
        			data_1.put("color", dataInfo.getKeywordColor_1());
        			data_2.put("color", dataInfo.getKeywordColor_2());
        			data_3.put("color", dataInfo.getKeywordColor_3());
        			data_4.put("color", dataInfo.getKeywordColor_4());
        			data_5.put("color", dataInfo.getKeywordColor_5());
        			data_6.put("color", dataInfo.getKeywordColor_6());
        			data_7.put("color", dataInfo.getKeywordColor_7());
        			data_8.put("color", dataInfo.getKeywordColor_8());
        			//data_r.put("color", dataInfo.getRemarkColor());
        			//
        			//data.put("first", data_f);
        			data.put("keyword1", data_1);
        			data.put("keyword2", data_2);
        			data.put("keyword3", data_3);
        			data.put("keyword4", data_4);
        			data.put("keyword5", data_5);
        			data.put("keyword6", data_6);
        			data.put("keyword7", data_7);
        			data.put("keyword8", data_8);
        			//data.put("remark", data_r);
			}
         } catch (JSONException e) {
            logger.error(e.getMessage());
         }
        return data;
    }
    /**
     * 
     * @param dataInfo
     * @return
     */
    public static String noticeMessage(WeiXinPushMessageEntity dataInfo){
    	
    	// 设置数据
    	JSONObject data = setData(dataInfo);
    	
        //微信凭证，access_token
        String token = "";
		try {
			token = findAccessToken();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        String url = TEMPLATE_URL.replace("ACCESS_TOKEN", token);
        JSONObject json = new JSONObject();
        try {
            json.put("touser", dataInfo.getOpenId());
            json.put("template_id",dataInfo.getTemplate_id());
            json.put("form_id", dataInfo.getFormId());
            json.put("data", data);
            json.put("page", dataInfo.getPageUrl());
            json.put("color", dataInfo.getColor());
            json.put("emphasis_keyword", dataInfo.getEmphasis_keyword());
        } catch (JSONException e) {
            logger.error(e.getMessage());
        }
        String result = httpsRequest(url, "POST", json.toString());
        try {
            JSONObject resultJson = new JSONObject(result);
            String errmsg = (String) resultJson.get("errmsg");
            if(!"ok".equals(errmsg)){//如果为errmsg为ok，则代表发送成功。
                logger.error("发送失败");
                return "error";
            }
        } catch (JSONException e) {
            logger.error(e.getMessage());
        }
        return "ok";
    }
    private static String httpsRequest(String requestUrl, String requestMethod, String outputStr){
        try {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("content-type", "application/x-www-form-urlencoded");
            // 当outputStr不为null时向输出流写数据
            if (null != outputStr) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 从输入流读取返回内容
            InputStream inputStream = conn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            StringBuffer buffer = new StringBuffer();
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            // 释放资源
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            conn.disconnect();
            return buffer.toString();
        } catch (ConnectException ce) {
            logger.error("连接超时：{}");
        } catch (Exception e) {
            logger.error("https请求异常：{}");
        }
        return null;
    }

    static String findAccessToken() throws Exception{
    	AccessTokenEntity accessTokenEntity = getaccessToken();
    	if (accessTokenEntity != null) {
    		return accessTokenEntity.getAccessToken();
		}
    	return "";
    }
    
    public static AccessTokenEntity getaccessToken(){
    	return accessTokenEntityMapper.get(new AccessTokenEntity());
    }
}
